package com.py.credit.controller;

import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.py.credit.common.ServiceException;
import com.py.credit.common.logs.ExceptionLogger;
import com.py.credit.common.rest.RestServiceResult;
import com.py.credit.entity.BatchFeedbackEntity;
import com.py.credit.entity.BatchLog;
import com.py.credit.entity.DictEntity;
import com.py.credit.entity.StepLog;
import com.py.credit.entity.SysUser;
import com.py.credit.entity.Table;
import com.py.credit.entity.common.OptionalColumn;
import com.py.credit.entity.enums.BatchDetailFieldsEnum;
import com.py.credit.entity.enums.ResourceBatchLogFieldsEnum;
import com.py.credit.service.BatchFeedbackService;
import com.py.credit.service.BatchLogService;
import com.py.credit.service.RemoteBaseService;
import com.py.credit.service.StepLogService;
import com.py.credit.service.TableService;
import com.py.credit.service.impl.UntreatedFileShedule;
import com.py.credit.utils.ExcelUtil;
import com.py.credit.utils.MapCache;
import com.py.framework.core.annotation.IgnoreAuthority;
import com.py.framework.core.common.Page;
import com.py.framework.core.entity.SysUserEntity;
import com.py.framework.core.helper.HttpServletHelper;

/**
 * 文件导入日志
 * 
 * @author jicm
 * 
 */
@RestController
@RequestMapping(value = "/batchLog")
public class BatchLogController extends BaseController {

	private final static String FRONT_TABLE_ID = "batch";

	@Autowired
	private BatchLogService batchLogService;

	@Autowired
	private StepLogService stepLogService;

	@Autowired
	private TableService tableService;

	@Value("${absolutepath}")
	private String absolutepath;

	@Autowired
	private RemoteBaseService remoteBaseService;

	@Autowired
	private UntreatedFileShedule untreatedFileShedule;

	@Autowired
	private BatchFeedbackService batchFeedbackService;

	/**
	 * 获取初始化列
	 * 
	 * @return
	 */
	@RequestMapping(value = "/getOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getOptionalColums() {
		return new RestServiceResult<List<OptionalColumn>>(ResourceBatchLogFieldsEnum.getOptionalColumns());
	}

	@RequestMapping(value = "/getAdvancedConditionColumns.json")
	public RestServiceResult<List<OptionalColumn>> getAdvancedConditionColumns() {
		return new RestServiceResult<List<OptionalColumn>>(ResourceBatchLogFieldsEnum.getAdvancedConditionColumns());

	}

	/**
	 * @api {get} /batchLog/getBatchList.json 获取导入批次列表
	 * @apiName getTableList
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * 
	 * @apiParam {String} condition 查询条件(可选)
	 * @apiParam {int} limit 每页展示条数 (必需)
	 * @apiParam {int} page 当前页数 (必需)
	 * 
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":18,"data":[{"result":"S","start_time":1524754733000,"id":"EX-10000060873-1-20180426-1371","managerName":"超级管理员","type":"0","tableName":"欠缴电费信息"},{"result":"F","start_time":1524756816000,"id":"EX-10000060873-1-20180426-3796","managerName":"超级管理员","type":"0","tableName":"欠缴电费信息"},{"result":"S","start_time":1524756722000,"id":"EX-10000060873-1-20180426-4799","managerName":"超级管理员","type":"0","tableName":"欠缴电费信息"}]}
	 * 
	 */
	@RequestMapping(value = "/getBatchList.json")
	public RestServiceResult<List<Map<String, Object>>> getTableList(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {

		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTableList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// String[] configColumns = (String[]) MapCache.get(userInfo.getId() +
		// "_" +
		// FRONT_TABLE_ID);
		// List<String> showColumns = (configColumns == null ||
		// configColumns.length ==
		// 0)
		// ? ResourceBatchLogFieldsEnum.getDefaultShowColumnEN() :
		// Arrays.asList(configColumns);
		List<String> showColumns = ResourceBatchLogFieldsEnum.getDefaultShowColumnEN();
		List<Map<String, Object>> tableList = batchLogService.getByConditionForPage(showColumns, null, condition, page,
				userInfo);
		if (!CollectionUtils.isEmpty(tableList)) {
			Set<Integer> userIds = new HashSet<Integer>(tableList.size());
			for (Map<String, Object> m : tableList) {
				if (null != m && m.containsKey("managerId") && null != m.get("managerId")) {
					userIds.add(Integer.parseInt(String.valueOf(m.get("managerId"))));
				}
			}
			tableList = remoteBaseService.matchUserDeptName(tableList, result, token, userIds, "managerId",
					"managerName", "deptName");
		}
		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), tableList);
	}

	/**
	 * 手动选择展示列
	 * 
	 * @param columns
	 * @return
	 */
	@RequestMapping(value = "/addShowColunms.json")
	public RestServiceResult<String> addShowColunms(@RequestParam(value = "columns", required = true) String[] columns,
			HttpServletRequest request) {
		RestServiceResult<String> result = new RestServiceResult<String>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#addShowColunms", "未获取到当前用户信息！");
				return result;
			}

			String column = StringUtils.join(columns, ",");
			column = column + ",managerId" + ",areaName";
			MapCache.set(userInfo.getId() + "_" + FRONT_TABLE_ID, StringUtils.split(column, ","));
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		return result;
	}

	/**
	 * 
	 * @api {get} /batchLog/export.json 批次处理信息导出
	 * @apiName exportBookcontentList
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * @apiParam {String} showColumn 导出列的数组
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/export")
	public RestServiceResult<Object> exportBookcontentList(
			@RequestParam(value = "columnEN", defaultValue = "", required = true) String columnEN,
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletResponse response, HttpServletRequest request) {
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		List<SysUser> userList = new ArrayList<SysUser>();
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#exportBookcontentList", "未获取到当前用户信息！");
				return result;
			}
			userList.add(userInfo);
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// 导出结果限制1000条
		page.setLimit(1000);
		List<String> showColumns = JSONArray.parseArray(columnEN, String.class);
		showColumns.add("managerId");
		List<Map<String, Object>> tableList;
		try {
			tableList = batchLogService.getByConditionForPage(showColumns, null, condition, page, userInfo);
			if (!CollectionUtils.isEmpty(tableList)) {
				Set<Integer> userIds = new HashSet<Integer>(tableList.size());
				for (Map<String, Object> m : tableList) {
					if (null != m && m.containsKey("managerId") && null != m.get("managerId")) {
						userIds.add(Integer.parseInt(String.valueOf(m.get("managerId"))));
					}
				}
				tableList = remoteBaseService.matchUserDeptName(tableList,
						new RestServiceResult<List<Map<String, Object>>>(), token, userIds, "managerId", "managerName",
						"deptName");
			}
			ExcelUtil.downloadExcel(response, tableList, "批次处理信息", "批次处理信息", showColumns,
					ResourceBatchLogFieldsEnum.getOptionalColumns());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("批次处理信息导出异常，请稍后再试！");
			ExceptionLogger.error("批次处理信息导出异常！", e.getMessage(), e);
			return result;
		}
	}

	/**
	 * @api {get} /batchLog/tableForDept.json 获取当前用户的部门所绑定的表信息
	 * @apiName tableForDeptList
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * 
	 * @apiParam {String} code 库id(必须)
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":[{"tableId":200249,"resourceTitle":"欠缴电费信息","resourceId":"10000060873","summary":null,"managementStyle":null,"resourceCategory":null,"sharingType":null,"updateFrequency":null,"online":null,"dateOfPublication":null,"serviceUrl":null,"serviceType":null,"organisationName":null,"providerAddress":null,"metadataContact":null,"maintainerAddress":null,"deptName":null,"content":null,"providerContact":null,"type":null,"deptId":null,"maintainer":null,"updateTime":null,"rootId":null,"data":null},{"tableId":200250,"resourceTitle":"欠缴燃气信息","resourceId":"10000060882","summary":null,"managementStyle":null,"resourceCategory":null,"sharingType":null,"updateFrequency":null,"online":null,"dateOfPublication":null,"serviceUrl":null,"serviceType":null,"organisationName":null,"providerAddress":null,"metadataContact":null,"maintainerAddress":null,"deptName":null,"content":null,"providerContact":null,"type":null,"deptId":null,"maintainer":null,"updateTime":null,"rootId":null,"data":null}]}
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/tableForDept.json")
	public RestServiceResult<List<Table>> tableForDeptList(String code, HttpServletRequest request) {
		RestServiceResult<List<Table>> result = new RestServiceResult<List<Table>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#tableForDeptList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		Long deptId = null;
		if (StringUtils.isNotBlank(userInfo.getAllParentId())) {
			String[] pDepts = StringUtils.split(userInfo.getAllParentId(), ",");
			deptId = Long.parseLong(pDepts[0]);
		} else {
			deptId = userInfo.getOfficeId();
		}
		List<Table> tableList = batchLogService.tableForDeptList(userInfo.getAreaId(), deptId, code);
		return new RestServiceResult<List<Table>>(tableList);
	}

	/**
	 * @throws IOException
	 * @throws FileNotFoundException
	 * @api {get} /batchLog/doFile.json 上传附件
	 * @apiName doUploadMultiFile
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * 
	 * @apiSuccess {CommonsMultipartFile} file 文件
	 * @apiSuccess {String} tableId 表的id
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":[]}
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/doFile.json")
	public RestServiceResult<Object> doUploadMultiFile(@RequestParam(value = "file") CommonsMultipartFile file,
			@RequestParam(value = "tableId", required = true) int tableId,
			@RequestParam(value = "rootId", required = true) int rootId, HttpServletRequest request,
			HttpServletResponse response) throws FileNotFoundException, IOException {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#doUploadMultiFile", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		Table table = tableService.queryCubeById(tableId);
		table.setRootId(rootId);
		String batchId;
		try {
			batchId = batchLogService.doUploadFile(table, file, userInfo, absolutepath);
		} catch (ServiceException e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg(e.getMsg());
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("上传文件异常！");
			ExceptionLogger.error("BatchLogController#doUploadMultiFile", "上传文件异常！", e);
			return result;
		}
		// 添加处理流程日志
		stepLogService.addStepLog(batchId, "文件上传完成,请耐心等待处理结果。");

		// try {
		// untreatedFileShedule.run(absolutepath);
		// } catch (Exception e) {
		// result.setCode(RestServiceResult.CODE_UNKNOW);
		// result.setMsg("上传文件异常！");
		// ExceptionLogger.error("BatchLogController#doUploadMultiFile",
		// "上传文件异常！", e);
		// return result;
		// }
		return new RestServiceResult<Object>(batchId);
	}

	/**
	 * 
	 * @api {get} /batchLog/upLoadFileTask.do 处理上传文件定时任务
	 * @apiName upLoadFileTask
	 * @apiVersion 0.0.1
	 * @apiGroup 数据归集
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/upLoadFileTask.do")
	public RestServiceResult<Object> upLoadFileTask() {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try {
			Object data = untreatedFileShedule.run(absolutepath);
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#upLoadFileTask", "上传文件定时任务异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("上传附件定时任务异常！");
			return result;
		}
	}

	/**
	 *
	 * @api {get} /batchLog/upLoadFileTask.do 处理上传文件定时任务
	 * @apiName upLoadFileTask
	 * @apiVersion 0.0.1
	 * @apiGroup 数据归集
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@RequestMapping(value = "/getFileList.do")
	public RestServiceResult<Object> getFileList(@RequestParam(value = "batchId", defaultValue = "", required = true) String batchId,
												 @RequestParam(value = "idDel", defaultValue = "", required = false) String idDel,
												 @RequestParam(value = "tableId", defaultValue = "", required = true) Integer tableId) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try{

			List<Map<String, Object>> listDataMap = untreatedFileShedule.getFileList(absolutepath,batchId,tableId,idDel);
			result.setData(listDataMap);
			return result;
		}catch (Exception e){
			e.printStackTrace();
			ExceptionLogger.error("BatchLogController#upLoadFileTask", "上传文件定时任务异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("上传附件定时任务异常！");
			return result;
		}

	}
	/**
	 * 法人守信激励对象名单同步
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping(value = "/FrjlAutoPush.do")
	public RestServiceResult<Object> FrjlAutoPush() {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try {
			 batchLogService.FrjlAutoPush();
			
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#FrjlAutoPush", "法人守信激励对象数据同步定时任务异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("法人守信激励对象数据同步定时任务异常！");
			return result;
		}
	}
	/**
	 * 法人失信惩戒对象名单同步
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping(value = "/FrcjAutoPush.do")
	public RestServiceResult<Object> FrcjAutoPush() {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try {
			 batchLogService.FrcjAutoPush();
			
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#FrcjAutoPush", "法人失信惩戒对象数据同步定时任务异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("法人失信惩戒对象数据同步定时任务异常！");
			return result;
		}
	}
	/**
	 * 自然人失信惩戒对象名单同步
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping(value = "/ZrrcjAutoPush.do")
	public RestServiceResult<Object> ZrrcjAutoPush() {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try {
			 batchLogService.ZrrcjAutoPush();
			
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#ZrrcjAutoPush", "自然人失信惩戒对象数据同步定时任务异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("自然人失信惩戒对象数据同步定时任务异常！");
			return result;
		}
	}
	/**
	 * 自然人守信激励对象名单同步
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping(value = "/ZrrjlAutoPush.do")
	public RestServiceResult<Object> ZrrjlAutoPush() {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try {
			 batchLogService.ZrrjlAutoPush();
			
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#ZrrjlAutoPush", "自然人守信激励对象数据同步定时任务异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("自然人守信激励对象数据同步定时任务异常！");
			return result;
		}
	}
	
	/**
	 * 采集任务状态同步
	 * @return
	 */
	@IgnoreAuthority
	@RequestMapping(value = "/UpdateCollectionState.do")
	public RestServiceResult<Object> UpdateCollectionState () {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try {
			 batchLogService.UpdateCollectionState();
			
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#UpdateCollectionState", "采集任务状态同步定时任务异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("采集任务状态同步！");
			return result;
		}
	}
	/**
	 * @throws IOException
	 * @throws FileNotFoundException
	 * @api {get} /batchLog/stepLog.json 获取步骤日志列表
	 * @apiName getList
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * 
	 * @apiSuccess {String} batchId 批次id
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":[{"detail":{"id":"EX-10000060873-1-20180426-1371","target":200249,"datasourceId":1,"type":"0","managerId":1,"deptId":1,"realName":null,"startTime":1524754733000,"endTime":1524754733000,"result":"S","tcount":10,"scount":10,"fcount":0,"rcount":0,"waitCount":0,"num":0,"status":"2","updateStatus":null,"tableName":null,"deptName":null,"updateEnableTime":null},"logs":[{"id":13134,"batchId":"EX-10000060873-1-20180426-1371","logDesc":"文件上传完成,请耐心等待处理结果。","operTime":1524754733000},
	 *                    {"id":13135,"batchId":"EX-10000060873-1-20180426-1371","logDesc":"开始处理上传文件。","operTime":1524754733000},
	 *                    {"id":13141,"batchId":"EX-10000060873-1-20180426-1371","logDesc":"结束将Excel0到10行数据录入至清洗库。","operTime":1524754733000}]}]}
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/stepLog.json")
	public RestServiceResult<List<Map<String, Object>>> getList(
			@RequestParam(value = "batchId", defaultValue = "", required = true) String batchId)
			throws FileNotFoundException, IOException {
		BatchLog bl = batchLogService.select(batchId);
		List<StepLog> stepLog = stepLogService.selectList(batchId);
		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("detail", bl);
		resMap.put("logs", stepLog);
		List<Map<String, Object>> array = new ArrayList<Map<String, Object>>();
		array.add(resMap);
		return new RestServiceResult<List<Map<String, Object>>>(array);
	}

	/**
	 * @api {get} /batchLog/fileDownload.json 原文件下载
	 * @apiName fileDownload
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * 
	 * @apiSuccess {String} batchId 批次id
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":[]}
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/fileDownload.json")
	public RestServiceResult<Object> fileDownload(
			@RequestParam(defaultValue = "", required = true, value = "batchId") String batchId,
			HttpServletResponse response) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try {
			batchLogService.fileDownload(batchId, response, absolutepath);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("原文件下载异常，请稍后再试！");
			ExceptionLogger.error("BatchLogController#fileDownload",
					"原文件下载异常ERROR:" + e.getMessage() + ",batchId=" + batchId + ",path=" + absolutepath, e);
			return result;
		}
	}

	/**
	 * @api {get} /batchLog/logDownload.json 日志文件下载
	 * @apiName logDownload
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * 
	 * @apiSuccess {String} batchId 批次id
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {Object[]} data 结果集
	 *
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":null,"count":0,"data":[]}
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/logDownload.json")
	public RestServiceResult<Object> logDownload(
			@RequestParam(defaultValue = "", required = true, value = "batchId") String batchId,
			HttpServletResponse response) {
		RestServiceResult<Object> result = new RestServiceResult<Object>();
		try {
			batchLogService.logDownload(batchId, response, absolutepath);
			return result;
		} catch (Exception e) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("日志文件下载异常，请稍后再试！");
			ExceptionLogger.error("BatchLogController#logDownload",
					"日志文件下载异常ERROR:" + e.getMessage() + ",batchId=" + batchId + ",path=" + absolutepath, e);
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchLog/getLastUpload.json 获取最近5条的数据采集操作
	 * @apiName getLastUpload
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@ResponseBody
	@RequestMapping(value = "/getLastUpload.json")
	public RestServiceResult<List<Map<String, Object>>> getLastUpload(HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#doUploadMultiFile", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		Long topDeptId = userInfo.getOfficeId();
		String pIds = userInfo.getAllParentId();
		if (StringUtils.isNotBlank(pIds)) {
			String t = StringUtils.split(pIds, ",")[0];
			topDeptId = StringUtils.isNoneBlank(t) ? Long.valueOf(t) : topDeptId;
		}
		try {
			
			List<Map<String, Object>> data  =  new ArrayList<>();
			if(userInfo.getRoleName().equals("系统管理员")) {
				data= batchLogService.getLastUpload(topDeptId, userInfo.getAreaId(),
						userInfo.getOfficeId(), userInfo.getUserType(),userInfo.getId());
			}else if(userInfo.getRoleName().equals("部门管理员")){
				data= batchLogService.getLastUpload(topDeptId, userInfo.getAreaId(),
						userInfo.getOfficeId(), userInfo.getUserType(),userInfo.getId());
			}else {
				data= batchLogService.getLastUpload(topDeptId, userInfo.getAreaId(),
						userInfo.getOfficeId(), userInfo.getUserType(),userInfo.getId());
			}
			
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#getLastUpload", "获取最近5条的数据采集操作异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常，请稍后再试！");
			return result;
		}
	}


	/**
	 *
	 * @api {get} /batchLog/getDoubleLastUpload.json 获取最近5条的数据采集操作
	 * @apiName getLastUpload
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@ResponseBody
	@RequestMapping(value = "/getDoubleLastUpload.json")
	public RestServiceResult<List<Map<String, Object>>> getDoubleLastUpload(HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getDoubleLastUpload", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		Long topDeptId = userInfo.getOfficeId();
		String pIds = userInfo.getAllParentId();
		if (StringUtils.isNotBlank(pIds)) {
			String t = StringUtils.split(pIds, ",")[0];
			topDeptId = StringUtils.isNoneBlank(t) ? Long.valueOf(t) : topDeptId;
		}
		try {
			List<Map<String, Object>> data  =  new ArrayList<>();
			if(userInfo.getRoleName().equals("系统管理员")) {
				data= batchLogService.getDoubleLastUpload(topDeptId, userInfo.getAreaId(),
						null, userInfo.getUserType(),null);
			}else if(userInfo.getRoleName().equals("部门管理员")){
				data= batchLogService.getDoubleLastUpload(topDeptId, userInfo.getAreaId(),
						userInfo.getOfficeId(), userInfo.getUserType(),null);
			}else {
				data= batchLogService.getDoubleLastUpload(topDeptId, userInfo.getAreaId(),
						userInfo.getOfficeId(), userInfo.getUserType(),userInfo.getId());
			}
			
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#getDoubleLastUpload", "获取最近5条的数据采集操作异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常，请稍后再试！");
			return result;
		}
	}

	@ResponseBody
	@RequestMapping(value = "/getDoubleFrLastUpload.json")
	public RestServiceResult<List<Map<String, Object>>> getDoubleFrLastUpload(HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getDoubleFrLastUpload", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		Long topDeptId = userInfo.getOfficeId();
		String pIds = userInfo.getAllParentId();
		if (StringUtils.isNotBlank(pIds)) {
			String t = StringUtils.split(pIds, ",")[0];
			topDeptId = StringUtils.isNoneBlank(t) ? Long.valueOf(t) : topDeptId;
		}
		try {
			
			List<Map<String, Object>> data  =  new ArrayList<>();
			if(userInfo.getRoleName().equals("系统管理员")) {
				data= batchLogService.getDoubleFrLastUpload(topDeptId, userInfo.getAreaId(),
						userInfo.getOfficeId(), userInfo.getUserType(),userInfo.getId());
			}else if(userInfo.getRoleName().equals("部门管理员")){
				data= batchLogService.getDoubleFrLastUpload(topDeptId, userInfo.getAreaId(),
						userInfo.getOfficeId(), userInfo.getUserType(),userInfo.getId());
			}else {
				data= batchLogService.getDoubleFrLastUpload(topDeptId, userInfo.getAreaId(),
						userInfo.getOfficeId(), userInfo.getUserType(),userInfo.getId());
			}
			
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#getDoubleFrLastUpload", "获取最近5条的数据采集操作异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常，请稍后再试！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchLog/batchStepLog.json 采集过程
	 * @apiName batchStepLog
	 * @apiVersion 0.0.1
	 * @apiGroup
	 * @apiParam {String} batchId 批次ID
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@ResponseBody
	@RequestMapping(value = "/batchStepLog.json")
	public RestServiceResult<List<StepLog>> batchStepLog(
			@RequestParam(value = "batchId", defaultValue = "", required = true) String batchId) {
		RestServiceResult<List<StepLog>> result = new RestServiceResult<>();
		try {
			List<StepLog> stepLog = stepLogService.selectList(batchId);
			result.setData(stepLog);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#batchStepLog", "获取采集过程异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取采集过程异常！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchLog/getDetailOptionalColums.json 批次详情列头
	 * @apiName getDetailOptionalColums
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@RequestMapping(value = "/getDetailOptionalColums.json")
	public RestServiceResult<List<OptionalColumn>> getDetailOptionalColums() {
		return new RestServiceResult<List<OptionalColumn>>(BatchDetailFieldsEnum.getOptionalColumns());
	}

	/**
	 * 
	 * @api {get} /batchLog/getBatchDetail.json 获取批次详情信息
	 * @apiName getBatchDetail
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * @apiParam {Integer} tableId 数据表ID
	 * @apiParamExample {json} 请求参数示例 {"tableId":200426}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@ResponseBody
	@RequestMapping(value = "/getBatchDetail.json")
	public RestServiceResult<List<Map<String, Object>>> getBatchDetail(HttpServletRequest request, Page page,
			@RequestParam(value = "tableId", defaultValue = "", required = true) Integer tableId) {
  		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<>();
		// 获取当前用户信息
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getBatchDetail", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			List<Map<String, Object>> data = batchLogService
					.getBatchDetailForPage(BatchDetailFieldsEnum.getDefaultShowColumnEN(), page, userInfo, tableId);
			if (!CollectionUtils.isEmpty(data)) {
				Set<Integer> userIds = new HashSet<Integer>(data.size());
				for (Map<String, Object> m : data) {
					if (null != m && m.containsKey("managerId") && null != m.get("managerId")) {
						userIds.add(Integer.parseInt(String.valueOf(m.get("managerId"))));
					}
				}
				remoteBaseService.matchUserDeptName(data, new RestServiceResult<List<Map<String, Object>>>(), token,
						userIds, "managerId", "managerName", "deptName");
			}
			result.setCount(page.getTotalCount());
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#getBatchDetail", "获取数据采集详情异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取数据采集详情异常！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchLog/addFeedback.json 新增批次反馈
	 * @apiName addFeedback
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * @apiParam {Integer} tableId 数据资源表ID
	 * @apiParam {Integer} rootId 库ID
	 * @apiParam {String} type 反馈类型名称
	 * @apiParam {String} reason 反馈原因
	 * @apiParam {Integer} status 反馈状态
	 * @apiParamExample {json} 请求参数示例
	 *                  {"tableId":200426,"rootId":100000,"type":"本期无数据","reason":"本期无上报数据","status":1}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {String} result
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@ResponseBody
	@RequestMapping(value = "/addFeedback.json")
	public RestServiceResult<Object> addFeedback(HttpServletRequest request,
			@RequestParam(value = "tableId", defaultValue = "", required = true) Integer tableId,
			@RequestParam(value = "rootId", defaultValue = "", required = true) Integer rootId,
			@RequestParam(value = "type", defaultValue = "", required = true) String type,
			@RequestParam(value = "reason", defaultValue = "", required = true) String reason,
			@RequestParam(value = "status", defaultValue = "", required = true) String status) {
		RestServiceResult<Object> result = new RestServiceResult<>();
		if (StringUtils.isEmpty(type) || StringUtils.isEmpty(reason) || StringUtils.isEmpty(status)) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("请录入必填项内容");
			return result;
		}
		if (type.length() > 20) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("反馈类型字段超长，请重新修订");
			return result;
		}
		if (reason.length() > 500) {
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("反馈原因字段超长，请重新修订");
			return result;
		}
		// 获取当前用户信息
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getBatchDetail", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			BatchFeedbackEntity entity = new BatchFeedbackEntity();
			entity.setType(type);
			entity.setStatus(status);
			entity.setReason(reason);
			entity.setManagerId(userInfo.getId());
			batchFeedbackService.addBatchFeedBack(entity, tableId, rootId, userInfo, status);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#addFeedback", "新增批次反馈异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("新增批次反馈异常！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchLog/feedbackDetail.json 获取批次反馈详情
	 * @apiName feedbackDetail
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * @apiParam {String} batchId 批次ID
	 * @apiParamExample {json} 请求参数示例 {"batchId":"123456788999"}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@ResponseBody
	@RequestMapping(value = "/feedbackDetail.json")
	public RestServiceResult<BatchFeedbackEntity> feedbackDetail(HttpServletRequest request,
			@RequestParam(value = "batchId", defaultValue = "", required = true) String batchId) {
		RestServiceResult<BatchFeedbackEntity> result = new RestServiceResult<>();
		try {
			BatchFeedbackEntity data = batchFeedbackService.getFeedBackByBatchId(batchId);
			if (null != data && null != data.getManagerId()) {
				Set<Integer> ids = new HashSet<Integer>(1);
				ids.add(Integer.parseInt(String.valueOf(data.getManagerId())));
				RestServiceResult<List<SysUserEntity>> users = remoteBaseService.getUsersByIds(ids,
						HttpServletHelper.getUserToken(request));
				if (null != users && !CollectionUtils.isEmpty(users.getData())) {
					SysUserEntity user = users.getData().get(0);
					if (null != user && StringUtils.isNotEmpty(user.getUsername())) {
						data.setManagerName(user.getUsername());
					}
				}
			}
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#feedbackDetail", "获取批次反馈详情异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取批次反馈详情异常！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchLog/getFeedbackTypes.json 获取批次反馈类型字典数据
	 * @apiName getFeedbackTypes
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccess {Long} dictId 字典主表ID
	 * @apiSuccess {String} dtlKey KEY值
	 * @apiSuccess {String} dtlValue 字典值
	 * @apiSuccess {String} dtlEx 字典扩展
	 * @apiSuccess {int} orderBy 排序
	 * @apiSuccess {int} enabled 是否使用，1否，2是
	 * @apiSuccessExample {json} 成功返回结果
	 *                    {"code":0,"msg":"","count":0,"data":[{"dictId":12,"dtlKey":"0","dtlValue":"文件导入","dtlEx":null,"orderBy":1,"enabled":2},{"dictId":12,"dtlKey":"1","dtlValue":"接口","dtlEx":null,"orderBy":2,"enabled":2}]}
	 */
	@ResponseBody
	@RequestMapping(value = "/getFeedbackTypes.json")
	public RestServiceResult<List<DictEntity>> getFeedbackTypes() {
		try {
			return remoteBaseService.getDictByDictKey("PCFK");
		} catch (Exception e) {
			RestServiceResult<List<DictEntity>> result = new RestServiceResult<>();
			ExceptionLogger.error("BatchLogController#getDictByDictKey", "获取批次反馈类型异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("获取批次反馈类型异常！");
			return result;
		}
	}

	/**
	 * 
	 * @api {get} /batchLog/manualCollection.json 手工采集
	 * @apiName manualCollection
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * @apiParam {String} data 数据json
	 * @apiParam {Integer} tableId 数据资源表ID
	 * @apiParam {Integer} rootId 库ID
	 * @apiParamExample {json} 请求参数示例 {}
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 * @apiSuccessExample {json} 成功返回结果 {}
	 */
	@ResponseBody
	@RequestMapping(value = "/manualCollection.json")
	public RestServiceResult<JSONObject> manualCollection(HttpServletRequest request,
			@RequestParam(value = "data", defaultValue = "", required = true) String data,
			@RequestParam(value = "tableId", defaultValue = "", required = true) Integer tableId,
			@RequestParam(value = "contentId", defaultValue = "", required = true) Integer contentId,
			@RequestParam(value = "rootId", defaultValue = "", required = true) Integer rootId) {
		RestServiceResult<JSONObject> result = new RestServiceResult<>();
		// 获取当前用户信息
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getBatchDetail", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		try {
			batchLogService.manualCollection(data, tableId, rootId, userInfo, contentId);
			return result;
		} catch (ServiceException e) {
			// 捕获抛出的异常
			String error = e.getMsg();
			JSONObject jb = new JSONObject();
			jb.put("error", error);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg(error);
			result.setData(jb);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#manualCollection", "手工采集执行异常！ERROR:" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("手工采集执行异常！");
			return result;
		}
	}



	@RequestMapping(value = "/getDoubleBatchList.json")
	public RestServiceResult<List<Map<String, Object>>> getDoubleBatchList(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {

		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getDoubleBatchList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// String[] configColumns = (String[]) MapCache.get(userInfo.getId() +
		// "_" +
		// FRONT_TABLE_ID);
		// List<String> showColumns = (configColumns == null ||
		// configColumns.length ==
		// 0)
		// ? ResourceBatchLogFieldsEnum.getDefaultShowColumnEN() :
		// Arrays.asList(configColumns);
		List<String> showColumns = ResourceBatchLogFieldsEnum.getDefaultShowColumnEN();
		List<Map<String, Object>> tableList = batchLogService.getDoubleByConditionForPage(showColumns, null, condition, page,
				userInfo);
		if (!CollectionUtils.isEmpty(tableList)) {
			Set<Integer> userIds = new HashSet<Integer>(tableList.size());
			for (Map<String, Object> m : tableList) {
				if (null != m && m.containsKey("managerId") && null != m.get("managerId")) {
					userIds.add(Integer.parseInt(String.valueOf(m.get("managerId"))));
				}
			}
			tableList = remoteBaseService.matchUserDeptName(tableList, result, token, userIds, "managerId",
					"managerName", "deptName");
		}
		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), tableList);
	}


	@RequestMapping(value = "/getDoubleFrBatchList.json")
	public RestServiceResult<List<Map<String, Object>>> getDoubleFrBatchList(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {

		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getDoubleFrByConditionForPage", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// String[] configColumns = (String[]) MapCache.get(userInfo.getId() +
		// "_" +
		// FRONT_TABLE_ID);
		// List<String> showColumns = (configColumns == null ||
		// configColumns.length ==
		// 0)
		// ? ResourceBatchLogFieldsEnum.getDefaultShowColumnEN() :
		// Arrays.asList(configColumns);
		List<String> showColumns = ResourceBatchLogFieldsEnum.getDefaultShowColumnEN();
		List<Map<String, Object>> tableList = batchLogService.getDoubleFrByConditionForPage(showColumns, null, condition, page,
				userInfo);
		if (!CollectionUtils.isEmpty(tableList)) {
			Set<Integer> userIds = new HashSet<Integer>(tableList.size());
			for (Map<String, Object> m : tableList) {
				if (null != m && m.containsKey("managerId") && null != m.get("managerId")) {
					userIds.add(Integer.parseInt(String.valueOf(m.get("managerId"))));
				}
			}
			tableList = remoteBaseService.matchUserDeptName(tableList, result, token, userIds, "managerId",
					"managerName", "deptName");
		}
		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), tableList);
	}
	

	/**
	 *
	 * @api {get} /batchLog/getDoubleLastUpload.json 获取最近5条的数据采集操作
	 * @apiName getLastUpload
	 * @apiVersion 0.0.1
	 * @apiGroup 数据采集
	 * @apiSuccess {String} code 状态码:1 成功 -1 失败
	 * @apiSuccess {String} msg 错误信息
	 * @apiSuccess {int} count 结果集数据量
	 * @apiSuccess {String} data 结果集
	 */
	@ResponseBody
	@RequestMapping(value = "/getTenLastUpload.json")
	public RestServiceResult<List<Map<String, Object>>> getTenLastUpload(HttpServletRequest request) {
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(HttpServletHelper.getUserToken(request));
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getTenLastUpload", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		Long topDeptId = userInfo.getOfficeId();
		String pIds = userInfo.getAllParentId();
		if (StringUtils.isNotBlank(pIds)) {
			String t = StringUtils.split(pIds, ",")[0];
			topDeptId = StringUtils.isNoneBlank(t) ? Long.valueOf(t) : topDeptId;
		}
		try {
			List<Map<String, Object>> data  =  new ArrayList<>();
			if(userInfo.getRoleName().equals("系统管理员")) {
				data= batchLogService.getTenLastUpload(topDeptId, userInfo.getAreaId(),
						null, userInfo.getUserType(),null);
			}else if(userInfo.getRoleName().equals("部门管理员")){
				data= batchLogService.getTenLastUpload(topDeptId, userInfo.getAreaId(),
						userInfo.getOfficeId(), userInfo.getUserType(),null);
			}else {
				data= batchLogService.getTenLastUpload(topDeptId, userInfo.getAreaId(),
						userInfo.getOfficeId(), userInfo.getUserType(),userInfo.getId());
			}
			
			result.setData(data);
			return result;
		} catch (Exception e) {
			ExceptionLogger.error("BatchLogController#getDoubleLastUpload", "获取最近5条的数据采集操作异常！ERROR：" + e.getMessage(), e);
			result.setCode(RestServiceResult.CODE_UNKNOW);
			result.setMsg("系统异常，请稍后再试！");
			return result;
		}
	}
	

	@RequestMapping(value = "/getTenBatchList.json")
	public RestServiceResult<List<Map<String, Object>>> getTenBatchList(
			@RequestParam(value = "condition", defaultValue = "", required = true) String condition, Page page,
			HttpServletRequest request) {

		// condition="[{columnEN:\"batch_id\",value:\"EX-test-1-20180326-1174\",type:\"varchar\",fuzzy:fasle}]";
		String token = HttpServletHelper.getUserToken(request);
		RestServiceResult<List<Map<String, Object>>> result = new RestServiceResult<List<Map<String, Object>>>();
		// 获取当前用户信息
		RestServiceResult<SysUser> user = remoteBaseService.getCurrentUser(token);
		SysUser userInfo = null;
		if (RestServiceResult.CODE_SUCCESS == user.getCode()) {
			userInfo = user.getData();
			if (null == userInfo || userInfo.getId() <= 0) {
				result.setCode(RestServiceResult.CODE_UNKNOW);
				result.setMsg("系统异常，请稍后再试！");
				ExceptionLogger.error("BatchLogController#getDoubleBatchList", "未获取到当前用户信息！");
				return result;
			}
		} else {
			result.setCode(user.getCode());
			result.setMsg(user.getMsg());
			return result;
		}
		// String[] configColumns = (String[]) MapCache.get(userInfo.getId() +
		// "_" +
		// FRONT_TABLE_ID);
		// List<String> showColumns = (configColumns == null ||
		// configColumns.length ==
		// 0)
		// ? ResourceBatchLogFieldsEnum.getDefaultShowColumnEN() :
		// Arrays.asList(configColumns);
		List<String> showColumns = ResourceBatchLogFieldsEnum.getDefaultShowColumnEN();
		List<Map<String, Object>> tableList = batchLogService.getTenByConditionForPage(showColumns, null, condition, page,
				userInfo);
		if (!CollectionUtils.isEmpty(tableList)) {
			Set<Integer> userIds = new HashSet<Integer>(tableList.size());
			for (Map<String, Object> m : tableList) {
				if (null != m && m.containsKey("managerId") && null != m.get("managerId")) {
					userIds.add(Integer.parseInt(String.valueOf(m.get("managerId"))));
				}
			}
			tableList = remoteBaseService.matchUserDeptName(tableList, result, token, userIds, "managerId",
					"managerName", "deptName");
		}
		return new RestServiceResult<List<Map<String, Object>>>(page.getTotalCount(), tableList);
	}
}
